package comp.wxapi.service;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import comp.wxapi.handler.MessageHandler;
import comp.wxapi.utils.ConfigUtils;
import comp.wxapi.vo.RouteConfig;
import me.chanjar.weixin.common.api.WxMessageDuplicateChecker;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpMessageRouterRule;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;


@Service
public class MessageRouterService {
	
	@Autowired
	private WxMessageDuplicateChecker wxMessageDuplicateChecker;
	@Autowired
	private WxSessionManager wxSessionManager;
	
	/**
	 * 消息路由:消息事件派发
	 * @param wxMpXmlMessage
	 * @return
	 */
	public String messageRouter(WxMpXmlMessage wxMpXmlMessage) {
		WxMpMessageRouter router = new WxMpMessageRouter(null);
		router.setMessageDuplicateChecker(wxMessageDuplicateChecker);
		router.setSessionManager(wxSessionManager);
		router = loadRouterRule(router);
		String result = router.route(wxMpXmlMessage).toXml();
		router.shutDownExecutorService();
		return result;
	}
	
	/**
	 * 路由规则加载
	 * @param router
	 * @return
	 */
	public WxMpMessageRouter loadRouterRule(WxMpMessageRouter router) {
		List<RouteConfig> routeConfigs = new ArrayList<RouteConfig>();
		//小程序
		routeConfigs.addAll(ConfigUtils.getRouteConfig("com.qq.weixin.miniapp.notifyUrl", ""));
		//微信公众号
		routeConfigs.addAll(ConfigUtils.getRouteConfig("com.qq.weixin.mp.notifyUrl", "default"));
		//开放平台
		routeConfigs.addAll(ConfigUtils.getRouteConfig("com.qq.weixin.open.notifyUrl", "default"));
		//加载路由规则
		for (RouteConfig routeConfig : routeConfigs) {
			MessageHandler handler = new MessageHandler(routeConfig.getUrl());
			WxMpMessageRouterRule rule = router.rule().async(routeConfig.getAsync()).handler(handler);
			if(StringUtils.isNotEmpty(routeConfig.getMsgType())) {
				rule.msgType(routeConfig.getMsgType());
			}
			if(StringUtils.isNotEmpty(routeConfig.getContent())) {
				rule.content(routeConfig.getContent());
			}
			if(StringUtils.isNotEmpty(routeConfig.getContentReg())) {
				rule.rContent(routeConfig.getContentReg());
			}
			if(StringUtils.isNotEmpty(routeConfig.getEvent())) {
				rule.event(routeConfig.getEvent());
			}
			if(StringUtils.isNotEmpty(routeConfig.getEventKey())) {
				rule.eventKey(routeConfig.getEventKey());
			}
			if(StringUtils.isNotEmpty(routeConfig.getEventKeyReg())) {
				rule.eventKeyRegex(routeConfig.getEventKeyReg());
			}
			rule.next();
		}
		return router;
	}
}

